from flask import Blueprint, render_template, redirect, url_for, flash, request, current_app
from flask_login import login_required, current_user
from ...models import User, ProfileInfo, CarouselImage, db
from ...forms import ProfileForm
from ...utils import allowed_file
import os

# 创建蓝图
main_zyy = Blueprint('main_zyy', __name__)

@main_zyy.route('/')
@main_zyy.route('/index_zyy')
def index_zyy():
    """首页路由"""
    # 获取轮播图
    carousel_images = CarouselImage.query.filter_by(
        is_active=True
    ).order_by(CarouselImage.display_order).all()
    
    return render_template('main_zyy/index_zyy.html', carousel_images=carousel_images)

@main_zyy.route('/profile_zyy/<username>')
def profile_zyy(username):
    """个人主页路由"""
    user = User.query.filter_by(username=username).first_or_404()
    
    # 获取个人主页信息
    profile_sections = ProfileInfo.query.filter_by(
        user_id=user.id
    ).order_by(ProfileInfo.display_order).all()
    
    return render_template('main_zyy/profile_zyy.html',
                         user=user,
                         profile_sections=profile_sections)

@main_zyy.route('/edit_profile_zyy', methods=['GET', 'POST'])
@login_required
def edit_profile_zyy():
    """编辑个人主页路由"""
    form = ProfileForm()
    if form.validate_on_submit():
        # 处理图片上传
        image_url = None
        if 'image' in request.files:
            file = request.files['image']
            if file and allowed_file(file.filename):
                filename = f"{current_user.id}_{file.filename}"
                file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))
                image_url = f"/static/uploads/{filename}"
        
        # 创建或更新个人主页信息
        section_type = request.form.get('section_type', 'about_me')
        profile_info = ProfileInfo.query.filter_by(
            user_id=current_user.id,
            section_type=section_type
        ).first()
        
        if not profile_info:
            profile_info = ProfileInfo(user_id=current_user.id)
        
        profile_info.title = form.title.data
        profile_info.content = form.content.data
        profile_info.section_type = section_type
        if image_url:
            profile_info.image_url = image_url
        
        db.session.add(profile_info)
        db.session.commit()
        
        flash('个人主页信息已更新', 'success')
        return redirect(url_for('main_zyy.profile_zyy', username=current_user.username))
    
    return render_template('main_zyy/edit_profile_zyy.html', form=form) 